<?php

namespace App\Models\Kms\Fs;

use App\Models\BaseModel;
use App\Models\Kms\User\KmsUser;
use App\Models\Traits\KfSoftDeletes;
use Illuminate\Database\Eloquent\Relations\HasMany;

class FsDepartmentsModel extends BaseModel
{
    use KfSoftDeletes;

    protected $table = "kf_fs_departments";

    /**
     * @return HasMany
     */
    public function userRel(): HasMany
    {
        return $this->hasMany(KmsUser::class, "departmentId", "openDepartmentId")
                    ->where("rmsUserId", ">", 0)
                    ->select([
                        "id",
                        "userId",
                        "rmsUserId",
                        "name",
                        "nickname",
                        "departmentId"
                    ]);
    }


    /**
     * 部门用户树状结构数据
     *
     * @return array
     */
    public static function departmentUserTree(): array
    {
        $fsDepartments = FsDepartmentsModel::query()->with(["userRel"])->select([
            "openDepartmentId",
            "parentDepartmentId",
            "name",
            "memberCount",
            "order"
        ])->get()->keyBy("openDepartmentId")->toArray();

        $departmentUserTree = [];
        foreach ($fsDepartments as &$department) {
            if (!empty($department["parentDepartmentId"])) {
                $fsDepartments[$department["parentDepartmentId"]]["child"][] = &$department;
            } else {
                $departmentUserTree[] = &$department;
            }
        }

        return $departmentUserTree;
//        unset($fsDepartments);
//        $departmentUser = [];
//        foreach ($tree as $treeDepartment) {
//            $this->build(
//                $treeDepartment,
//                $departmentUser,
//                [collect($treeDepartment)->only(["openDepartmentId", "name"])->toArray()]
//            );
//        }
//
//        return $departmentUser;
    }

    /**
     * 构建部门用户数据
     *
     * @param array $department
     * @param array $departmentUser
     * @param array $groupDepartment
     */
    public static function build(array $department, array &$departmentUser, array $groupDepartment)
    {
        if (isset($department["child"])) {
            foreach ($department["child"] as $childDepartment) {
                $tempGroupDepartment = array_merge(
                    $groupDepartment,
                    [collect($childDepartment)->only(["openDepartmentId", "name"])->toArray()]
                );
                self::build(
                    $childDepartment,
                    $departmentUser,
                    $tempGroupDepartment
                );
            }
        } else {
            array_push($departmentUser, [
                "department" => $groupDepartment,
                "user"       => $department["user_rel"]
            ]);
        }
    }
}
